#include "map_window.h"
#include "ui_manager.h"
#include <iostream>
#include <webkit2/webkit2.h>

MapWindow::MapWindow() {
    builder = nullptr;
    window = nullptr;
    web_view = nullptr;
}

MapWindow::~MapWindow() {
    if (builder) {
        g_object_unref(builder);
    }
}

// 确保目录存在的辅助函数
static void ensure_directory_exists(const gchar* path) {
    if (!g_file_test(path, G_FILE_TEST_IS_DIR)) {
        g_mkdir_with_parents(path, 0755);
        g_print("Created directory: %s\n", path);
    }
}

bool MapWindow::init() {
    // 1. 加载UI文件（原有逻辑保留）
    builder = gtk_builder_new();
    std::string ui_path = UIManager::get_ui_path();
    size_t pos = ui_path.find_last_of("/");
    
    if (pos != std::string::npos) {
        ui_path = ui_path.substr(0, pos) + "/map_window.glade";
    } else {
        ui_path = "./UI/map_window.glade";
    }

    GError *error = nullptr;
    if (!gtk_builder_add_from_file(builder, ui_path.c_str(), &error)) {
        std::cerr << "无法加载UI文件 " << ui_path << ": " << error->message << std::endl;
        g_error_free(error);
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }

    // 获取窗口和容器
    window = GTK_WIDGET(gtk_builder_get_object(builder, "map_window"));
    if (!window) {
        std::cerr << "无法获取map_window对象" << std::endl;
        g_object_unref(builder);
        builder = nullptr;
        return false;
    }

    GtkWidget* map_container = GTK_WIDGET(gtk_builder_get_object(builder, "map_container"));
    if (!map_container) {
        g_error("map_container not found in Glade file");
        g_object_unref(builder);
        return false;
    }

    // 获取新添加的组件
    btn_openUrl = GTK_WIDGET(gtk_builder_get_object(builder, "btn_openUrl"));
    edUrl = GTK_WIDGET(gtk_builder_get_object(builder, "edUrl"));
    
    if (!btn_openUrl || !edUrl) {
        g_warning("btn_openUrl or edUrl not found in Glade file");
    } else {
        // 连接按钮点击事件
        g_signal_connect(btn_openUrl, "clicked", G_CALLBACK(on_open_url_clicked), this);
    }

    // 清除容器原有控件
    GList* children = gtk_container_get_children(GTK_CONTAINER(map_container));
    if (children) {
        gtk_container_remove(GTK_CONTAINER(map_container), GTK_WIDGET(children->data));
        g_list_free(children);
    }

    // 2. 核心修复：正确创建带数据管理器的WebContext（类型转换修正）
    gchar* data_dir = g_strdup("./webkit_data");
    ensure_directory_exists(data_dir);
    g_print("Set persistent data directory: %s\n", data_dir);

    // 步骤1：创建数据管理器
    // 创建数据管理器时，添加 Cookie 接受策略
    WebKitWebsiteDataManager* data_manager = webkit_website_data_manager_new(
        "base-data-directory", data_dir,
        nullptr
    );
    // WebKitWebsiteDataManager* data_manager = webkit_website_data_manager_new(
    //     "base-data-directory", data_dir,
    //     nullptr
    // );

    // 步骤2：修复类型转换！用WEBKIT_WEB_CONTEXT宏转换，而非G_OBJECT
    // 原因：g_object_new返回GObject*，需用WebKit专用宏转为WebKitWebContext*
    WebKitWebContext* custom_context = WEBKIT_WEB_CONTEXT(
        g_object_new(WEBKIT_TYPE_WEB_CONTEXT,  // 指定创建WebKitWebContext类型对象
                    "website-data-manager", data_manager,  // 构造时绑定管理器
                    nullptr)  // 终止参数列表
    );

    // 正确设置 Cookie 接受策略：WebKitWebsiteDataManager 不接受 "cookie-accept-policy" 属性。
    // 应通过 WebKit 的 CookieManager 来设置接受策略。
    WebKitCookieManager* cookie_manager = webkit_web_context_get_cookie_manager(custom_context);
    if (cookie_manager) {
        webkit_cookie_manager_set_accept_policy(cookie_manager, WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS);
    }

    // 3. 设置扩展目录和创建WebView
    const gchar* extension_dir = "./extensions/extension";
    webkit_web_context_set_web_extensions_directory(custom_context, extension_dir);
    g_print("扩展目录已设置为: %s\n", extension_dir);

    // 用自定义Context创建WebView
    web_view = WEBKIT_WEB_VIEW(webkit_web_view_new_with_context(custom_context));

    // 4. 开发者工具和URL加载
    WebKitSettings* settings = webkit_web_view_get_settings(web_view);
    webkit_settings_set_enable_developer_extras(settings, TRUE);

    // WebKitWebInspector* inspector = webkit_web_view_get_inspector(web_view);
    // webkit_web_inspector_show(inspector);

    

    webkit_web_view_load_uri(web_view, "http://www.qrz.cn");

    // 5. 组装UI和释放资源
    gtk_container_add(GTK_CONTAINER(map_container), GTK_WIDGET(web_view));
    gtk_widget_set_hexpand(GTK_WIDGET(web_view), TRUE);
    gtk_widget_set_vexpand(GTK_WIDGET(web_view), TRUE);

    gtk_builder_connect_signals(builder, nullptr);

    g_free(data_dir);
    return true;
}

void MapWindow::open_map(const std::string& url) {
    if (web_view) {
        webkit_web_view_load_uri(web_view, url.c_str());
        std::cout << "已加载URL: " << url << std::endl;
    } else {
        std::cerr << "WebView未初始化，无法加载URL: " << url << std::endl;
    }
}

void MapWindow::show() {
    if (window) {
        gtk_widget_show_all(window);
    }
}

void MapWindow::hide() {
    if (window) {
        gtk_widget_hide(window);
    }
}

GtkWidget* MapWindow::get_window() {
    return window;
}

void MapWindow::on_open_url_clicked(GtkWidget* widget, gpointer data) {
    MapWindow* window = static_cast<MapWindow*>(data);
    
    // 获取输入框中的文本
    const gchar* url_text = gtk_entry_get_text(GTK_ENTRY(window->edUrl));
    
    // 检查URL是否为空
    if (url_text && strlen(url_text) > 0) {
        // 在web_view中打开URL
        webkit_web_view_load_uri(window->web_view, url_text);
    }
}